package com.chebaohui.iqs.service.impl.deal.bihu.profess;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.chebaohui.iqs.config.BiHuConfig;
import com.chebaohui.iqs.config.CompanyCode;
import com.chebaohui.iqs.config.ResultCode;
import com.chebaohui.iqs.entity.base.Cars;
import com.chebaohui.iqs.entity.base.Company;
import com.chebaohui.iqs.entity.req.CheckCar;
import com.chebaohui.iqs.entity.res.CompanyCars;
import com.chebaohui.iqs.service.impl.deal.bihu.entity.req.CarCheck;
import com.chebaohui.iqs.service.impl.deal.bihu.num.SixInterface;
import com.chebaohui.iqs.service.impl.deal.bihu.utils.EnumUtil;
import com.chebaohui.iqs.service.impl.deal.util.CompanyUtil;
import com.chebaohui.iqs.service.impl.deal.util.StringUtil;

/**
 * 对外输出<针对车保汇后台>--车辆查询
 * 
 * @author xielonghai
 *
 */
public class BiHuCarCheck {
	private CheckCar carParam;// 查车参数

	private List<CompanyCars<List<Cars>>> result;// 查车结果

	private Map<String, Boolean> mapCode;// 所需返回保险公司编码集合

	/**
	 * @param carParam
	 *            查车请求参数
	 */
	public BiHuCarCheck(CheckCar carParam, Map<String, Boolean> mapCode) {
		super();
		this.mapCode = mapCode;
		this.result = new ArrayList<>();
		this.carParam = carParam;
	}

	/**
	 * 获取接口
	 * 
	 * @return
	 */
	public List<CompanyCars<List<Cars>>> check() {
		try {
			return bhCheckCar();
		} catch (Exception e) {
			List<CompanyCars<List<Cars>>> res = new ArrayList<>();
			for (String key : mapCode.keySet()) {
				if (mapCode.get(key)) {
					CompanyCars<List<Cars>> c = new CompanyCars<List<Cars>>(key, ResultCode.N02.getCode(),
							ResultCode.N02.getMsg() + e.getMessage());
					res.add(c);
				}
			}
			return res;
		}
	}

	/**
	 * 查车
	 * 
	 * @param carParam
	 *            查车参数
	 * @return
	 */
	public List<CompanyCars<List<Cars>>> bhCheckCar() throws Exception {
		CarCheck param = new CarCheck();
		param.setCustKey(BiHuConfig.getCustKey());//
		param.setLicenseNo(carParam.getLicense().getLicenceNo());// 车牌
		param.setMoldName(carParam.getLicense().getLableNo());// 厂牌
		param.setEngineNo(carParam.getLicense().getEngineNo());// 发动机
		param.setCarVin(carParam.getLicense().getFrameNo());// 车架

		JSONArray items = null;
		if (carParam.getLicense().getFrameNo().indexOf("L") != 0) {// 进口车车架号非“L”开头，需先用车架号查出车型厂牌，在用厂牌获取车型列表
			param.setIsNeedCarVin(1);
			items = bihuCheck(param);
			param.setIsNeedCarVin(0);
			param.setMoldName(CompanyUtil.labelNoDeal(items.getJSONObject(0).getString("VehicleName")));// 厂牌
		}
		items = bihuCheck(param);

		for (int i = 0; i < items.size(); i++) {// 遍历壁虎返回车型列表
			JSONObject car = items.getJSONObject(i);
			setCompangCarList(EnumUtil.getCombination(car.getDoubleValue("Source")), car);
		}
		for (String key : mapCode.keySet()) {
			if (mapCode.get(key)) {
				CompanyCars<List<Cars>> c = new CompanyCars<List<Cars>>(key, ResultCode.N04.getCode(),
						ResultCode.N04.getMsg() + "无此车型");
				result.add(c);
			}
		}

		new BiHuRenewal().bihuiRenewalCar(result,carParam);
		


		return result;
	}		

	/**
	 * 调壁虎6号接口车辆查询
	 * 
	 * @param param
	 * @return
	 * @throws Exception
	 */
	private JSONArray bihuCheck(CarCheck param) throws Exception {
		JSONObject cars = new SixInterface().six(param);// 调壁虎6号接口车辆查询

		if (null == cars || cars.isEmpty())
			throw new Exception("壁虎车辆查询失败:返回null");

		if (!"1".equals(cars.getString("BusinessStatus").trim()))
			throw new Exception("壁虎车辆查询失败:" + cars.getString("StatusMessage"));
		JSONArray items = cars.getJSONArray("Items");
		if (null == items || items.isEmpty())
			throw new Exception("壁虎车辆查询失败:车型列表为空");
		return items;
	}

	/**
	 * 设置返回车型列表
	 * 
	 * @param sources
	 * @param car
	 */
	private void setCompangCarList(List<Double> sources, JSONObject car) {
		for (Double d : sources) {// 遍历保险公司枚举
			getCompanySet(EnumUtil.getSource(d), car);
		}
	}

	/**
	 * 根据要求保险公司编码设定返回车型列表
	 * 
	 * @param code
	 * @param car
	 */
	private void getCompanySet(CompanyCode code, JSONObject car) {
		if (null == code)
			return;
		for (Company c : carParam.getCompanys()) {// 遍历需要返回保险公司列表集（即请求参数中要求返回保险公司的code列表）
			if (code.getCode().equals(c.getCompanyCode()))
				setCarList(car, code.getCode());
		}
	}

	/**
	 * 车型列表设置
	 * 
	 * @param car
	 * @param companyCode
	 */
	private void setCarList(JSONObject car, String companyCode) {
		if (StringUtil.isNulls(companyCode))
			return;
		boolean company = true;
		for (CompanyCars<List<Cars>> c : result) {// 遍历返回结果集
			if (c.getCompanyCode().equals(companyCode)) {
				company = false;
				setCar(c, car);// 已有列表添加车型
			}
		}

		if (company) {
			for (String key : mapCode.keySet()) {// 所需保险公司车型确定有
				if (key.equals(companyCode))
					mapCode.put(key, false);
			}
			CompanyCars<List<Cars>> c = new CompanyCars<List<Cars>>(companyCode, ResultCode.SUCCESS.getCode(),
					ResultCode.SUCCESS.getMsg());
			setCar(c, car);// 新建列表添加车型
			result.add(c);
		}
	}

	/**
	 * 车型详细设置
	 * 
	 * @param c
	 * @param car
	 */
	private void setCar(CompanyCars<List<Cars>> c, JSONObject car) {
		List<Cars> cc = c.getCars();
		if (null == cc) {
			cc = new ArrayList<>();
			c.setCars(cc);// 至关重要---null本身来说，它不是对象，在返回结果中必须对null写入实际对象
		}
		Cars cs = new Cars();
		cs.setModelCode(car.getString("VehicleNo"));
		if (StringUtil.isNulls(cs.getModelCode())){// 精友车型编码为空时，用车辆购置价格替代《2017-12-22改》
			String price=car.getString("PurchasePrice").substring(0, car.getString("PurchasePrice").indexOf('.'));
			cs.setModelCode(price);
		}

		cs.setModelName(car.getString("VehicleName"));
		cs.setExhausMeasur(car.getString("VehicleExhaust"));
		cs.setSaleDate(car.getString("VehicleYear"));
		cs.setPurchase(car.getString("PurchasePrice"));
		cs.setRemark(car.getString("VehicleAlias"));
		cs.setSeats(car.getIntValue("VehicleSeat"));
		cc.add(cs);
	}


}
